package com.pgytesting.secondhandcar.service.impl;

import com.pgytesting.secondhandcar.dao.McpUserOtherInformationDao;
import com.pgytesting.secondhandcar.model.McpCarDealerInformation;
import com.pgytesting.secondhandcar.dao.McpCarDealerInformationDao;
import com.pgytesting.secondhandcar.model.McpUserInfo;
import com.pgytesting.secondhandcar.model.McpUserOtherInformation;
import com.pgytesting.secondhandcar.service.McpCarDealerInformationService;
import com.pgytesting.secondhandcar.util.SessionUtil;
import com.pgytesting.secondhandcar.util.UtilMethod;
import com.pgytesting.secondhandcar.vo.Parameters;
import com.pgytesting.secondhandcar.vo.ResponseMessage;
import com.pgytesting.secondhandcar.vo.SMSCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售信息(McpCarDealerInformation)表服务实现类
 *
 * @author makejava
 * @since 2019-08-15 14:48:18
 */
@Slf4j
@Service("mcpCarDealerInformationService")
public class McpCarDealerInformationServiceImpl implements McpCarDealerInformationService {
    @Resource
    private McpCarDealerInformationDao mcpCarDealerInformationDao;

    @Resource
    private McpUserOtherInformationDao otherInformationDao;

    /**
     * 通过ID查询单条数据
     *
     * @param phoneNumber 主键
     * @return 实例对象
     */
    @Override
    public McpCarDealerInformation queryById(String phoneNumber) {
        return this.mcpCarDealerInformationDao.queryById(phoneNumber);
    }

    /**
     * 条件查询多条数据
     *
     * @param mcpCarDealerInformation 实例对象
     * @return 对象列表
     */
    @Override
    public List<McpCarDealerInformation> queryAll(McpCarDealerInformation mcpCarDealerInformation) {
        return this.mcpCarDealerInformationDao.queryAll(mcpCarDealerInformation);
    }

    /**
     * 新增数据
     *
     * @param mcpCarDealerInformation 实例对象
     * @return 实例对象
     */
    @Override
    public ResponseMessage insert(McpCarDealerInformation mcpCarDealerInformation) {
        // 进行短信验证码校验
        SMSCode smsCode = SessionUtil.getSessionSMSCode();
        if (smsCode == null) {
            return ResponseMessage.errorResponse("未查询到短信验证码或已被使用，请重新获取");
        } else if (smsCode.getCurrentTime() <= UtilMethod.unixLong()) {
            ResponseMessage.errorResponse("短信验证码过期");
        } else if (!mcpCarDealerInformation.getSmsCode().equals(smsCode.getSmsCode())) {
            return ResponseMessage.errorResponse("短信验证码错误");
        } else if (!mcpCarDealerInformation.getPhoneNumber().equals(smsCode.getPhoneNumber())) {
            return ResponseMessage.errorResponse("短信验证码与手机号不符");
        }
        // 验证通过移除短信验证码
        SessionUtil.removeSMSCode();
        if (mcpCarDealerInformationDao.queryCount(mcpCarDealerInformation) != null) {
            return ResponseMessage.errorResponse("手机号已被注册");
        }
        // 添加账号唯一识别码
        mcpCarDealerInformation.setUserNumber(UtilMethod.getUniqueCode());
        // 密码加密处理
        mcpCarDealerInformation.setPassword(UtilMethod.md5Encryption(mcpCarDealerInformation.getPassword()));
        Integer affected = 1;

        try {
            while (affected > 0) {
                mcpCarDealerInformation.setCarDealerInvitationCode(UtilMethod.randomCode());
                affected = this.mcpCarDealerInformationDao.queryCarCode(mcpCarDealerInformation);
            }
            affected = this.mcpCarDealerInformationDao.insert(mcpCarDealerInformation);
        } catch (
                DuplicateKeyException e) {
            return ResponseMessage.errorResponse("手机号已被注册");
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            return ResponseMessage.errorResponse("注册用户异常");
        }
        // 进行用户其他信息添加
        McpUserOtherInformation otherInformation = new McpUserOtherInformation();
        otherInformation.setUserNumber(mcpCarDealerInformation.getUserNumber());
        otherInformation.setUserPhoneNumber(mcpCarDealerInformation.getPhoneNumber());
        try {
            affected = otherInformationDao.insert(otherInformation);
        } catch (Exception e) {
            log.error("用户其他信息插入失败，进行数据库回退");
            this.mcpCarDealerInformationDao.deleteById(otherInformation.getUserPhoneNumber());
            log.error(e.getLocalizedMessage());
            return ResponseMessage.errorResponse("注册用户异常");
        }
        if (affected < 1) {
            try {
                this.mcpCarDealerInformationDao.deleteById(otherInformation.getUserPhoneNumber());
                otherInformationDao.deleteById(otherInformation.getUserNumber());
            } catch (Exception e) {
                return ResponseMessage.errorResponse("注册用户异常，数据回退异常，请联系管理员");
            }
            return ResponseMessage.errorResponse("注册用户失败");
        }
        // 创建新变量将车商邀请码返回前端
        McpCarDealerInformation mcpCar = new McpCarDealerInformation();
        mcpCar.setCarDealerInvitationCode(mcpCarDealerInformation.getCarDealerInvitationCode());
        return ResponseMessage.successResponse(mcpCar, "注册用户成功");
    }

    /**
     * 修改数据
     *
     * @param mcpCarDealerInformation 实例对象
     * @return 实例对象
     */
    @Override
    public ResponseMessage updatePhone(McpCarDealerInformation mcpCarDealerInformation) {
        // 进行变量转移，防止利用后台修改其他数据
        McpCarDealerInformation mcpCar = new McpCarDealerInformation();
        mcpCar.setSmsCode(mcpCarDealerInformation.getSmsCode());
        mcpCar.setPhoneNumber(mcpCarDealerInformation.getPhoneNumber());
        // 进行短信验证码校验
        SMSCode smsCode = SessionUtil.getSessionSMSCode();
        if (smsCode == null) {
            return ResponseMessage.errorResponse("未查询到短信验证码或已被使用，请重新获取");
        } else if (smsCode.getCurrentTime() <= UtilMethod.unixLong()) {
            ResponseMessage.errorResponse("短信验证码过期");
        } else if (!mcpCar.getSmsCode().equals(smsCode.getSmsCode())) {
            return ResponseMessage.errorResponse("短信验证码错误");
        } else if (!mcpCar.getPhoneNumber().equals(smsCode.getPhoneNumber())) {
            return ResponseMessage.errorResponse("短信验证码与手机号不符");
        }
        // 验证通过移除短信验证码
        SessionUtil.removeSMSCode();
        // 通过session中存储的信息获取用户信息
        mcpCar.setUserNumber(SessionUtil.getSessionMcpCar().getUserNumber());
        Integer updateCount = 0;
        try {
            updateCount = this.mcpCarDealerInformationDao.update(mcpCar);
        } catch (Exception e) {
            log.error("修改绑定手机号异常", e.getLocalizedMessage());
            return ResponseMessage.errorResponse("修改绑定手机号异常");
        }
        if (updateCount < 1) {
            return ResponseMessage.errorResponse("修改绑定手机号失败");
        }
        return ResponseMessage.successResponse("修改绑定手机号成功");
    }


    /**
     * 通过主键删除数据
     *
     * @param phoneNumber 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String phoneNumber) {
        return this.mcpCarDealerInformationDao.deleteById(phoneNumber) > 0;
    }

    /**
     * 销售登录
     *
     * @param mcpCar 登录
     * @return
     */
    @Override
    public ResponseMessage queryLogin(McpCarDealerInformation mcpCar) {
        // 对密码进行md5加密处理
        mcpCar.setPassword(UtilMethod.md5Encryption(mcpCar.getPassword()));
        McpCarDealerInformation dealerInformation;
        try {
            dealerInformation = this.mcpCarDealerInformationDao.queryLogin(mcpCar);
            SessionUtil.updateSession("login", Parameters.USER_TYPE_CAR);
            SessionUtil.updateSession("user", dealerInformation);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            return ResponseMessage.errorResponse("登录信息获取异常");
        }
        if (dealerInformation == null) {
            return ResponseMessage.errorResponse("账号密码错误或者不存在");
        }

        return ResponseMessage.successResponse(dealerInformation,"登陆成功");
    }

    @Override
    public McpCarDealerInformation queryByUserNumber(String userNumber) {
        return mcpCarDealerInformationDao.queryByUserNumber(userNumber);
    }

    @Override
    public ResponseMessage getUserInf() {
        String userNumber = SessionUtil.getSessionMcpCar().getUserNumber();
        McpCarDealerInformation information = mcpCarDealerInformationDao.queryByUserNumber(userNumber);
        McpCarDealerInformation mcpCarDealerInformation = new McpCarDealerInformation();
        mcpCarDealerInformation.setUserNumber(information.getUserNumber());
        mcpCarDealerInformation.setPhoneNumber(information.getPhoneNumber());
        mcpCarDealerInformation.setCarDealerInvitationCode(information.getCarDealerInvitationCode());
        return ResponseMessage.successResponse(mcpCarDealerInformation, "查询成功");
    }
}